<template>
  <div class="information-container">
    <div class="headerphoto">
      <slot name="back" style="left:0;"></slot>
      <div class="Photo">
      <span class="photo">更换头像</span>
      </div>
    </div>
        <div class="imageCountainer">
          <el-upload
          class="upload-demo"
          :action="uploadImgUrl"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :auto-upload="false" 
          :limit="limit"
          :on-error="handleUploadError"
          ref="imageUpload"
          :show-file-list="true"       
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :class="{hide: this.fileList.length >= this.limit}">
          <i class="el-icon-plus" style=" margin-top: 5rem"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img :src="dialogImageUrl" alt="">
        </el-dialog>
        </div>
        <button class="sure" @click="confirmFn()">确定上传</button>
  </div>

</template>

<script>
import {getChild,huanavatar} from '@/api/myInfo/index'

export default {
  name: 'UserAvatar',
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
       type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    val: {
      tyle: String,
      default: ''
    }
  },
  data () {
    return {
      avatar: '',
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      studnetId:'',
      growKey:'',
      remark:'',
      growthId:'',
      uploadImgUrl:"", // 上传的图片服务器地址
      fileList: []
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              if (item.indexOf(this.baseUrl) === -1) {
                  item = { name: this.baseUrl + item, url: this.baseUrl + item };
              } else {
                  item = { name: item, url: item };
              }
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  async created(){
        if(this.val!==''){
          sessionStorage.setItem("studnetId",this.val)
          this.studnetId=sessionStorage.getItem('studnetId')
        }else{
          this.studnetId=sessionStorage.getItem('studnetId')
        }
        // console.log(this.studnetId)
        // console.log(" 111",this.studnetId)
        this.uploadImgUrl=process.env.VUE_APP_BASE_API+`/business/students/avatar/`+this.studnetId
        // 上传的图片服务器地址
        // console.log(process.env.VUE_APP_BASE_API+`/business/students/avatar`+'?'+'studentId='+this.studentId)
      //   this.fileList.push({
      //   url:this.fileList.url
      // })
  }, 
  methods: {
    async changephoto(){
          this.studentId=parseInt(this.studentId)
          const res =await huanavatar({studnetId:this.studentId})
          this.huanList = res.data
          console.log(this.huanList)
      },
      async gets(){
        const res = await getChild({})
        // console.log(res.data)
        this.childList = res.data
        console.log(res)
        // console.log("111",this.childList)   
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.$message({
        message: '头像上传成功',
        type: 'success'
        });
      } else {
        this.$message({
        message: '上传失败,请重新上传',
        type: 'error'
        });
      }
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
    },
    // 上传结束处理
    uploadedSuccessfully() {
      // if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        console.log(this.fileList,"fileList")
        console.log( "6666",this.fileList[1])
        this.uploadList = [];
        this.$emit("input", this.listToString(this.fileList));
        //  this.fileList.push({
            // url:`http://localhost/dev-api${fileList.url}`
        // })
        console.log()
      // }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    confirmFn(){
        this.studnetId=this.val
        console.log(" 111",this.studnetId)
        this.uploadImgUrl=process.env.VUE_APP_BASE_API+`/business/students/avatar/`+this.studnetId
        this.$refs.imageUpload.submit();
        // window.location.reload();
        this.gets()
    },
    // 选择图片->点击事件->让选择框出现
    chooseImg () {
      // 模拟点击行为
      this.$refs.iptRef.click()
    },
    // 在选择框中选择图片后触发的改变事件
    onFileChange (e) {
      // 获取用户选择的文件列表（伪数组）
      const files = e.target.files
      if (files.length === 0) {
        // 没有选择图片
        this.avatar = ''
      } else {
        // 选择了图片
        console.log(files[0])
      }
    },
    
    reload () {//局部刷新
    this.isShow = false;
    this.$nextTick(() => {
      this.isShow = true
    })
  },
  },
  onFileChange(e) {
  const files = e.target.files
  if (files.length === 0) {
    this.avatar = ''
  } else {
    // 1. 创建 FileReader 对象
    const fr = new FileReader()
    // 2. 调用 readAsDataURL 函数，读取文件内容
    fr.readAsDataURL(files[0])
    // 3. 监听 fr 的 onload 事件
    fr.onload = e => {
      // 4. 通过 e.target.result 获取到读取的结果，值是字符串（base64 格式的字符串）
      this.avatar = e.target.result
    }
  }
  },
}
</script>

<style scoped>

/*整个盒子 */
.information-container {
  height:44.375rem;
  display: flex;
  width: 100%;
  flex-direction: column;
  border: .0625rem solid rgba(245, 245, 245, 1);
  position: relative;

  width:10rem;
  max-width:120rem;
  min-width:85.375rem;
  margin:0 auto;
  line-height:1.5;
}
 /* 头部更换头像 */
 .headerphoto{
    height: 3.6875rem;
    display: flex;
    align-items: center;
    /* justify-content: center; */
    border: .0625rem solid rgba(245, 245, 245, 1);
    width: 100%;
 }
 .box{
  margin-top:6.25rem;
 }

 .Photo{
  align-items: center;
 }
 .photo{
    font-size: 1.5625rem;
    margin-left:36.25rem;
 }
.preview {
  object-fit: cover;
}
.the_img{
    width: 21.875rem;
    height: 21.875rem;
}
/*包两个盒子的按钮 */
.btn-box{
  margin-top:1.25rem;
}
/*确定上传按钮 */
.sure{
  width: 12.5rem;
  height: 3.75rem;
  margin-top: 31.25rem;
  margin-left: 36.5625rem!important;
  border-radius: 6%;
  cursor:pointer;
  background-color:#7c0000;
  color:#fff;
  border:#7c0000;
}

.el-button--primary{
  background-color:#fff;
  color:black;
}
/*选择图片按钮 */
.change{
  width: 7.5rem;
  height: 2.1875rem;
  border-radius: 6%;
}

.upload-demo /deep/ .el-upload--picture-card{
  position: absolute;
  z-index: 2;
  height: 18.75rem !important;
  width: 18.75rem !important;
  border: .0625rem solid rgba(124, 0, 0, 1);
  border-style: dashed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 0;
}

.el-icon-plus:before{
  content: "\A\E6D9\A上传头像" !important;
  font-size:1.25rem !important;
  white-space:pre !important;
  color: rgba(124, 0, 0, 1);
}

.imageCountainer{
  position: absolute;
  z-index: 3;
  height: 18.75rem !important;
  width: 18.75rem !important;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 0;
}

.upload-demo /deep/ .el-upload-list--picture-card .el-upload-list__item{
z-index: 3;
height: 18.75rem !important;
width: 18.75rem !important;
}

</style>

